package com.feinno.urcs.group.http.handler;

import com.feinno.urcs.group.GroupError;
import com.feinno.urcs.group.GroupException;
import com.feinno.urcs.group.entity.GroupIndex;
import com.feinno.urcs.group.http.servlet.BaseHttpServlet;
import com.feinno.urcs.group.http.servlet.GroupHttpContext;
import com.feinno.urcs.group.http.util.HttpHelper;
import com.feinno.urcs.group.http.util.StringHelper;
import com.feinno.urcs.group.pd.upstream.entity.PublicGroup_List_Entry;
import com.feinno.urcs.group.pd.util.Content;
import com.feinno.urcs.group.pd.util.MultiPartContent;
import com.feinno.urcs.nai.IMPU;
import com.feinno.urcs.types.MobileNo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wuzhiguo on 15-5-14.
 */
public class


		GroupInviteHandler extends BaseHttpServlet {

	private static final Logger LOGGER = LoggerFactory.getLogger(GroupInviteHandler.class);

	@Override
	public void process(final GroupHttpContext ctx) throws IOException {
		try {
			if (LOGGER.isInfoEnabled()) {
				String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
				LOGGER.info(String.format("Received Request: %s", requestString));
			}

//            if (ctx.getTargetIMPU() == null) {
//                String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
//                LOGGER.error(String.format("targetIMPU is null. Received Request: %s", requestString));
//                ctx.getResponse().sendError(400, "ArgsError");
//                return;
//            }
			byte[] requestBody = ctx.getBodyString().getBytes();
			String charSet = ctx.getRequest().getCharacterEncoding();
			String boundary = getBoundary(ctx.getRequest().getContentType());
			MultiPartContent multiPartContent = new MultiPartContent();
			if (charSet == null) {
				multiPartContent.setCharset("utf-8");
			}
			if (boundary == null) {
				ctx.getResponse().sendError(400, "ArgsError");
				return;
			}
			multiPartContent.setBoundary(boundary);
			multiPartContent.parseContentList(requestBody);
			List<Content> contentList = multiPartContent.getContentList();
			List<MobileNo> list = new ArrayList<>();
			boolean isError = false;
			for (Content content : contentList) {
				String str = new String(content.getContent());
				PublicGroup_List_Entry entry = getEntryImpu(str);
				if (entry == null) {
					String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
					LOGGER.error(String.format("getEntryImpu is null. Received Request: %s", requestString));
					isError = true;
					break;
				}
				IMPU entryImpu = IMPU.parse(entry.getUri());
				list.add(MobileNo.parseFrom(entryImpu.getUser()));
//				if (!entryImpu.equals(ctx.getTargetIMPU())) {
//					String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
//					LOGGER.error(String.format("entryImpu not equals targetIMPU. Received Request: %s", requestString));
//					try {
//						ctx.getResponse().sendError(400, "ArgsError");
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//					return;
//				}
			}
			if (isError) {
				ctx.getResponse().sendError(400, "ArgsError");
				return;
			}
			MobileNo[] invitees = new MobileNo[list.size()];
			// 调用GroupService
//			GroupIndex groupIndex = new GroupIndex(getGroupIdFromUri(ctx.getXuiIMPU().toString()), 0);
			int groupId = getGroupIdFromUri(ctx.getXuiIMPU().toString());
			GroupIndex groupIndex = ctx.getGroupService().getGroupIndex(groupId);
			ctx.getGroupService().inviteGroupMembers(groupIndex, MobileNo.parseFrom(ctx.getSenderIMPU().getUser()), list.toArray(invitees));
			ctx.getResponse().setStatus(202);
			ctx.getResponse().setHeader("ETag", "0");
			setDigestAuthenticationInfo(ctx);
			ctx.getResponse().setContentLength(0);
			if (LOGGER.isInfoEnabled()) {
				String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
				LOGGER.info(String.format("process() Successfully. Received Request: %s", requestString));
			}

		} catch (GroupException gex) {
			GroupError error = gex.getError();
			String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
			LOGGER.error(String.format("process() GroupException. GroupError Code: %s Received Request: %s",
					error.getSipCode(), requestString), gex);
			ctx.getResponse().sendError(error.getSipCode(), error.getText());
		} catch (Exception ex) {
			String requestString = HttpHelper.getRequestString(ctx.getRequest(), ctx.getBodyString());
			LOGGER.error(String.format("process() Error. Received Request: %s", requestString), ex);
			ctx.getResponse().sendError(500, "ServerError");
		}
	}

	private String getBoundary(String contentType) {
		int index = contentType.indexOf("boundary");
		if (index == -1) {
			return null;
		}
		String[] strings = contentType.split(";");
		if (!strings[0].equals("multipart/mixed")) {
			return null;
		}
		return contentType.substring(index + 9);
	}

	private PublicGroup_List_Entry getEntryImpu(String body) {
		try {
			PublicGroup_List_Entry entry = new PublicGroup_List_Entry();
			entry.parseXmlFrom(body);
			if (!StringHelper.isNullOrEmpty(entry.getUri())) {
				return entry;
			}
		} catch (Exception ex) {
			LOGGER.error(String.format("getEntryImpu() Error. Received Request: %s", body), ex);
		}
		return null;
	}
}
